var logger = global.logger;
var usermgr = global.usermgr;

module.exports = function(roomid){
    return new Room(roomid);
}

var Room = function(roomid){
    this.roomid = roomid;
    this.players = [];
    this.state = this.RoomState.Prepate;
    this.gamelogic = null;
}

Room.prototype.RoomState = {
    Prepate: 1,
    Game: 2,
}

Room.prototype.joinWithAccount = function(account){
    
    if(this.state == this.RoomState.Game){
        logger.warn('该房间在游戏中，不可加入');
        return;
    }

    if(this.players.indexOf(account) != -1){
        logger.warn('不可重复加入：' + account);
        return;
    }

    var userinstance = usermgr.get(account);
    if(userinstance){
        this.players.push(account);
        userinstance.roomId = this.roomid;
        this.checkGameStart();
    }
    else{
        logger.error('账号不存在:' + account);
    }
}

Room.prototype.checkGameStart = function(){
    var GameLogic = require('../gamelogic');
    var GamePlayer = require('./gameplayer');

    if(this.players.length == 2){
        this.state = this.RoomState.Game;
        
        this.gamelogic = new GameLogic(this);
        this.gamelogic.StartGame(new GamePlayer(usermgr.get(this.players[0])), new GamePlayer(usermgr.get(this.players[1])));
    }
}

Room.prototype.broadcastAll = function(route, msg){
    for(var i = 0; i < this.players.length; i++){
        var user = usermgr.get(this.players[i]);
        if(user){
            user.push(route, msg);
        }
        else{
            logger.warn('房间有玩家离线了：' + this.players[i]);
        }     
    }
}

Room.prototype.broadcastWithoutSender = function(senderAcount){
    for(var i = 0; i < this.players.length; i++){
        if(senderAcount != this.players[i]){
            var user = usermgr.get(this.players[i]);
            if(user){
                user.push(route, msg);
            }
            else{
                logger.warn('房间有玩家离线了：' + this.players[i]);
            }    
        }
    }
}
